<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('team.generateInviteCode')"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="top"
    >
      <el-form-item :label="$t('team.inviteRole')" prop="inviteRole">
        <el-radio-group v-model="form.inviteRole">
          <!-- {{ AURA-X: Modify - 修复Element Plus兼容性，将label改为value. Approval: 寸止(ID:fix-element-plus). }} -->
          <el-radio value="MEMBER">{{ $t('team.memberRole') }}</el-radio>
          <el-radio value="ADMIN">{{ $t('team.adminRole') }}</el-radio>
        </el-radio-group>
        <div class="form-tip">
          {{ $t('team.inviteRoleTip') }}
        </div>
      </el-form-item>

      <el-form-item :label="$t('team.expireTime')" prop="expireTime">
        <el-date-picker
          v-model="form.expireTime"
          type="datetime"
          :placeholder="$t('team.expireTimePlaceholder')"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DDTHH:mm:ss"
          :disabled-date="disabledDate"
          :disabled-hours="disabledHours"
          :disabled-minutes="disabledMinutes"
          style="width: 100%"
        />
        <div class="form-tip">
          {{ $t('team.expireTimeTip') }}
        </div>
      </el-form-item>

      <el-form-item :label="$t('team.maxUses')" prop="maxUses">
        <el-input-number
          v-model="form.maxUses"
          :min="1"
          :max="100"
          :step="1"
          :placeholder="$t('team.maxUsesPlaceholder')"
          style="width: 100%"
        />
        <div class="form-tip">
          {{ $t('team.maxUsesTip') }}
        </div>
      </el-form-item>

      <!-- 预设选项 -->
      <el-form-item :label="$t('team.quickSettings')">
        <div class="quick-settings">
          <el-button 
            size="small" 
            @click="setQuickOption('1hour')"
          >
            {{ $t('team.oneHour') }}
          </el-button>
          <el-button 
            size="small" 
            @click="setQuickOption('1day')"
          >
            {{ $t('team.oneDay') }}
          </el-button>
          <el-button 
            size="small" 
            @click="setQuickOption('1week')"
          >
            {{ $t('team.oneWeek') }}
          </el-button>
          <el-button 
            size="small" 
            @click="setQuickOption('unlimited')"
          >
            {{ $t('team.unlimited') }}
          </el-button>
        </div>
      </el-form-item>

      <!-- 预览信息 -->
      <el-card class="preview-card" shadow="never">
        <template #header>
          <span>{{ $t('team.codePreview') }}</span>
        </template>
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item :label="$t('team.inviteRole')">
            <el-tag :type="getMemberRoleType(form.inviteRole)" size="small">
              {{ getMemberRoleLabel(form.inviteRole) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('team.expireTime')">
            {{ form.expireTime || $t('team.neverExpire') }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('team.maxUses')">
            {{ form.maxUses || $t('team.unlimited') }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
        >
          {{ $t('team.generateCode') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormInstance, FormRules } from 'element-plus'
import { useTeamStore } from '@/stores/teamStore'
import type { GenerateInviteCodeRequest } from '@/types/team'
import { getMemberRoleLabel, getMemberRoleType } from '@/types/team'

interface Props {
  modelValue: boolean
  teamId: number
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()

const teamStore = useTeamStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = reactive<GenerateInviteCodeRequest>({
  inviteRole: 'MEMBER',
  expireTime: '',
  maxUses: 10
})

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单验证规则
const rules: FormRules = {
  inviteRole: [
    { required: true, message: t('team.inviteRoleRequired'), trigger: 'change' }
  ],
  expireTime: [
    { 
      validator: (rule, value, callback) => {
        if (value && new Date(value) <= new Date()) {
          callback(new Error(t('team.expireTimeInvalid')))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  maxUses: [
    { type: 'number', min: 1, max: 100, message: t('team.maxUsesRange'), trigger: 'blur' }
  ]
}

// 方法
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const disabledHours = () => {
  const now = new Date()
  const selectedDate = form.expireTime ? new Date(form.expireTime) : null
  
  if (!selectedDate || selectedDate.toDateString() !== now.toDateString()) {
    return []
  }
  
  const hours = []
  for (let i = 0; i < now.getHours(); i++) {
    hours.push(i)
  }
  return hours
}

const disabledMinutes = (hour: number) => {
  const now = new Date()
  const selectedDate = form.expireTime ? new Date(form.expireTime) : null
  
  if (!selectedDate || 
      selectedDate.toDateString() !== now.toDateString() || 
      hour !== now.getHours()) {
    return []
  }
  
  const minutes = []
  for (let i = 0; i <= now.getMinutes(); i++) {
    minutes.push(i)
  }
  return minutes
}

const setQuickOption = (option: string) => {
  const now = new Date()
  
  switch (option) {
    case '1hour':
      form.expireTime = new Date(now.getTime() + 60 * 60 * 1000).toISOString().slice(0, 19)
      form.maxUses = 5
      break
    case '1day':
      form.expireTime = new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString().slice(0, 19)
      form.maxUses = 10
      break
    case '1week':
      form.expireTime = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 19)
      form.maxUses = 20
      break
    case 'unlimited':
      form.expireTime = ''
      form.maxUses = null
      break
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const requestData: GenerateInviteCodeRequest = {
      inviteRole: form.inviteRole,
      expireTime: form.expireTime || undefined,
      maxUses: form.maxUses || undefined
    }
    
    await teamStore.generateInviteCode(props.teamId, requestData)
    
    emit('success')
    resetForm()
  } catch (error) {
    console.error('生成邀请码失败:', error)
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    inviteRole: 'MEMBER',
    expireTime: '',
    maxUses: 10
  })
}

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible) {
    resetForm()
  }
})
</script>

<style scoped lang="scss">
.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
  line-height: 1.4;
}

.quick-settings {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.preview-card {
  margin-top: 20px;
  
  :deep(.el-card__header) {
    padding: 12px 20px;
    background: var(--el-bg-color-page);
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }

  .quick-settings {
    .el-button {
      flex: 1;
      min-width: 80px;
    }
  }
}
</style>
